<?php namespace Phpcmf\Controllers\Api;

// 通用接口处理
class Api extends \Phpcmf\Common
{

    /**
     * 搜索
     */
    public function search() {

        $dir = dr_safe_replace(\Phpcmf\Service::L('Input')->get('dir'));
        !$dir && $this->_msg(0, dr_lang('模块参数不能为空'));
        $keyword = dr_safe_replace(\Phpcmf\Service::L('Input')->get('keyword'));
        // 跳转url
        dr_redirect(\Phpcmf\Service::L('Router')->search_url([], 'keyword', $keyword, $dir));
    }

    /**
     * 检查关键字
     */
    public function checktitle() {

        // 获取参数
        $id = (int)\Phpcmf\Service::L('Input')->get('id');
        $title = dr_safe_replace(\Phpcmf\Service::L('Input')->get('title'));
        $module = dr_safe_replace(\Phpcmf\Service::L('Input')->get('module'));

        // 判断参数
        (!$title || !$module) && exit('');

        // 判断模块
        !\Phpcmf\Service::L('cache')->get('module-'.SITE_ID.'-'.$module) && exit('');

        // 判断是否重复存在
        $num = \Phpcmf\Service::M()->db->table(SITE_ID.'_'.$module)->where('id<>', $id)->where('title', $title)->countAllResults();
        $num ? exit(dr_lang('重复')) : exit('');
    }

    /**
     * 提取关键字
     */
    public function getkeywords() {

        $kw = dr_get_keywords(dr_safe_replace(\Phpcmf\Service::L('Input')->get('title')));
        exit($kw);
    }

    /**
     * 存储临时表单内容
     */
    public function save_form_data() {

        $rt = \Phpcmf\Service::L('cache')->init('file')->save(
            \Phpcmf\Service::L('Input')->get('name'),
            \Phpcmf\Service::L('Input')->post('data'),
            7200
        );
        var_dump($rt);
        exit;
    }

    /**
     * 删除临时表单内容
     */
    public function delete_form_data() {
        \Phpcmf\Service::L('cache')->init('file')->delete(\Phpcmf\Service::L('Input')->get('name'));
        $this->_json(1, dr_lang('清除成功'));
        exit;
    }

    /**
     * 验证码
     */
    public function captcha() {

        $code = \Phpcmf\Service::L('captcha')->create();
        $this->session()->set('captcha', $code);
        exit();
    }

    /**
     * 汉字转换拼音
     */
    public function pinyin() {
        $name = dr_safe_replace(\Phpcmf\Service::L('Input')->get('name'));
        !$name && exit('');
        $py = \Phpcmf\Service::L('pinyin')->result($name);
        if (strlen($py) > 12) {
            $sx = \Phpcmf\Service::L('pinyin')->result($name, 0);
            $sx && exit($sx);
        }
        exit($py);

    }


    /**
     * 联动菜单调用
     */
    public function linkage() {

        $pid = (int)\Phpcmf\Service::L('Input')->get('parent_id');
        $code = \Phpcmf\Service::L('Input')->get('code');
        $linkage = \Phpcmf\Service::L('cache')->get('linkage-'.SITE_ID.'-'.$code);

        $json = array();
        foreach ($linkage as $v) {
            $v['pid'] == $pid && $json[] = array('region_id' => $v['ii'], 'region_name' => $v['name']);
        }

        echo json_encode($json);exit;
    }

    /**
     * Ajax调用字段属性表单
     *
     * @return void
     */
    public function field() {

        $id = (int)\Phpcmf\Service::L('Input')->get('id');
        $app = dr_safe_replace(\Phpcmf\Service::L('Input')->get('app'));
        $type = dr_safe_replace(\Phpcmf\Service::L('Input')->get('type'));

        // 关联表
        \Phpcmf\Service::M('field')->relatedid = dr_safe_replace(\Phpcmf\Service::L('Input')->get('relatedid'));
        \Phpcmf\Service::M('field')->relatedname = dr_safe_replace(\Phpcmf\Service::L('Input')->get('relatedname'));

        // 获取全部字段
        $all = \Phpcmf\Service::M('field')->get_all();
        $data = $id ? $all[$id] : null;
        $value = $data ? $data['setting']['option'] : []; // 当前字段属性信息

        list($option, $style) = \Phpcmf\Service::L('field')->app($app)->option($type, $value, $all);

        exit(json_encode(['option' => $option, 'style' => $style]));
    }


    /**
     * 动态调用模板
     */
    public function template() {

        ob_start();
        \Phpcmf\Service::V()->display(dr_safe_replace(\Phpcmf\Service::L('Input')->get('name')));
        $html = ob_get_contents();
        ob_clean();

        $this->_jsonp(1, $html);
    }

    /**
     * 内容关联字段数据读取
     */
    public function related() {

        // 强制将模板设置为后台
        \Phpcmf\Service::V()->admin();

        // 登陆判断
        !$this->uid && $this->_json(0, dr_lang('会话超时，请重新登录'));

        // 参数判断
        $dirname = dr_safe_filename(\Phpcmf\Service::L('Input')->get('module'));
        !$dirname && $this->_json(0, dr_lang('module参数不存在'));

        // 站点选择
        $site = max(1, (int)$_GET['site']);

        // 模块缓存判断
        $module = $this->get_cache('module-'.$site.'-'.$dirname);
        !$module && $this->_json(0, dr_lang('模块（%s）不存在', $dirname));

        $module['field']['id'] = array(
            'name' => 'Id',
            'ismain' => 1,
            'fieldtype' => 'Text',
            'fieldname' => 'id',
        );

        $builder = \Phpcmf\Service::M()->db->table($site.'_'.$dirname);

        if ($this->member['id'] == 1) {
            $module['field']['author'] = array(
                'name' => dr_lang('作者'),
                'ismain' => 1,
                'fieldtype' => 'Text',
                'fieldname' => 'author',
            );
        } else {
            $builder->where('uid', $this->uid);
        }

        // 搜索结果显示条数
        $limit = (int)$_GET['limit'];
        $limit = $limit ? $limit : 50;


        if (IS_POST) {
            $ids = \Phpcmf\Service::L('Input')->get_post_ids();
            !$ids && $this->_json(0, dr_lang('没有选择项'));
            $id = array();
            foreach ($ids as $i) {
                $id[] = (int)$i;
            }
            $builder->whereIn('id', $id);
            $list = $builder->limit($limit)->orderBy('updatetime DESC')->get()->getResultArray();
            !$list && $this->_json(0, dr_lang('没有相关数据'));
            $rt = [];
            foreach ($list as $t) {
                $rt[] = [
                    'id' => $t['id'],
                    'value' => '<a href="'.$t['url'].'" tagreg="_blank">'.$t['title'].'</a>'
                ];
            }
            $this->_json(1, dr_lang('操作成功'), ['result' => $rt]);
        }

        $data = $_GET;

        if ($data['search']) {
            $catid = (int)$data['catid'];
            $catid && $builder->whereIn('catid', $module['category'][$catid]['catids']);
            $data['keyword'] = dr_safe_replace(urldecode($data['keyword']));
            if (isset($data['keyword']) && $data['keyword']
                && $data['field'] && isset($module['field'][$data['field']])) {
                $data['keyword'] = dr_safe_replace(urldecode($data['keyword']));
                if ($data['field'] == 'id') {
                    // id搜索
                    $id = array();
                    $ids = explode(',', $data['keyword']);
                    foreach ($ids as $i) {
                        $id[] = (int)$i;
                    }
                    $builder->whereIn('id', $id);
                } else {
                    // 其他模糊搜索
                    $builder->like($data['field'], $data['keyword']);
                }
            }
        }

        sort($module['field']);
        $db = $builder->limit($limit)->orderBy('updatetime DESC')->get();
        $list = $db ? $db->getResultArray() : [];

        \Phpcmf\Service::V()->assign(array(
            'list' => $list,
            'param' => $data,
            'field' => $module['field'],
            'select' => \Phpcmf\Service::L('tree')->select_category(
                $module['category'],
                $data['catid'],
                'name="catid"',
                '--'
            ),
            'category' => $module['category'],
            'search' => dr_form_search_hidden(['search' => 1, 'module' => $dirname, 'site' => $site, 'limit' => $limit]),
        ));
        \Phpcmf\Service::V()->display('api_related.html');exit;
    }

    /**
     * 退出前台账号
     */
    public function loginout() {

        $this->_json(1, dr_lang('您的账号已退出系统'), [
            'url' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : SITE_URL,
            'sso' => \Phpcmf\Service::M('member')->logout(),
        ]);
    }



}
